import 'dart:math';

import 'package:flutter/material.dart';
import 'package:shining_red_star/api/list_count_ducks_result_aud.dart';
import 'package:shining_red_star/definitions/color.dart';
import 'package:shining_red_star/utils/play.dart';
import '../../wrappers/safe-area.dart';
import '../api/list_count_ducks_aud.dart';
import '../definitions/icon_font.dart';
import '../model/duck.dart';
import '../widgets/focus_manage/focus_widget.dart';

class CountDucksPage extends StatefulWidget {
  const CountDucksPage({super.key});

  @override
  State<CountDucksPage> createState() => _CountDucksPageState();
}

class _CountDucksPageState extends State<CountDucksPage> {
  final FocusNode focusNode = FocusNode();
  final FocusNode duckWrapFocusNode = FocusNode();
  int count = Random().nextInt(10) + 1;
  int lastTotalActiveDucks = 0;
  List<DuckInfoState> duckInfoListCache = [];
  bool forcedRefresh = true;
  Size duckSize = Size(96, 96);
  List<CountDucksAudInfo> countDucksAudList = [];
  List<CountDucksAudInfo> countDucksResultAudList = [];

  void loadData() {
    listCountDucksAud().then((res) {
      setState(() {
        countDucksAudList = res;
      });
    });
    listCountDucksResultAud().then((res) {
      setState(() {
        countDucksResultAudList = res;
      });
    });
  }

  bool isOverlap(Rect rect1, Rect rect2) {
    if (rect1.left < rect2.left + rect2.size.width &&
        rect1.left + rect1.size.width > rect2.left &&
        rect1.top < rect2.top + rect2.size.height &&
        rect1.top + rect1.size.height > rect2.top) {
      return true;
    }
    return false;
  }

  bool isOverlapWithExistingDucks(Rect duckRect, List<DuckInfoState> ducks) {
    for (DuckInfoState existingDuckInfo in ducks) {
      if (isOverlap(duckRect, existingDuckInfo.rect)) {
        return true;
      }
    }
    return false;
  }

  Offset getRandomPosition(
      Size wrapSize, Size duckSize, List<DuckInfoState> ducks) {
    while (true) {
      double x = Random().nextDouble() * (wrapSize.width - duckSize.width);
      double y = Random().nextDouble() * (wrapSize.height - duckSize.height);
      Rect duckRect = Rect.fromLTWH(
        x,
        y,
        duckSize.width,
        duckSize.height,
      );
      if (!isOverlapWithExistingDucks(duckRect, ducks)) {
        return Offset(x, y);
      }
    }
  }

  List<DuckInfoState> getDuckInfoList(Size size) {
    if (!forcedRefresh && duckInfoListCache.isNotEmpty) {
      return duckInfoListCache;
    }
    forcedRefresh = false;
    duckInfoListCache.clear();
    for (int i = 0; i < count; i++) {
      Offset duckOffset = getRandomPosition(size, duckSize, duckInfoListCache);
      Rect duckRect = Rect.fromLTWH(
          duckOffset.dx, duckOffset.dy, duckSize.width, duckSize.height);
      duckInfoListCache.add(DuckInfoState(
          duckIconData: IconFontValue.normalDuck, rect: duckRect));
    }
    return duckInfoListCache;
  }

  int? pointIndex(Offset localPosition) {
    for (int i = 0; i < duckInfoListCache.length; i++) {
      Rect duckRect = duckInfoListCache[i].rect;
      if (duckRect.contains(localPosition)) {
        return i;
      }
    }
    return null;
  }

  void changeDuckStatus(DuckInfoState duckInfo, bool focus, bool tab) {
    if (tab) {
      if (focus) {
        duckInfo.duckIconData = IconFontValue.focusAndActiveDuck;
      } else {
        duckInfo.duckIconData = IconFontValue.activeDuck;
      }
    } else if (duckInfo.duckIconData == IconFontValue.activeDuck ||
        duckInfo.duckIconData == IconFontValue.focusAndActiveDuck) {
      if (focus) {
        duckInfo.duckIconData = IconFontValue.focusAndActiveDuck;
      } else {
        duckInfo.duckIconData = IconFontValue.activeDuck;
      }
    } else if (focus) {
      duckInfo.duckIconData = IconFontValue.focusDuck;
    } else {
      duckInfo.duckIconData = IconFontValue.normalDuck;
    }
  }

  Widget renderTitle() {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(bottom: 20),
      child: FocusWidget(
          autofocus: true,
          focusNode: focusNode,
          onConfirm: () {
            setState(() {
              lastTotalActiveDucks = 0;
              count = Random().nextInt(10) + 1;
              forcedRefresh = true;
            });
          },
          onFocusChange: (bool value) {
            setState(() {});
          },
          child: Text('数鸭子（共 $count 只）',
              style: TextStyle(
                  fontSize: 22,
                  color: focusNode.hasFocus
                      ? SchemeColor.seedColor.value
                      : null))),
    );
  }

  Widget renderDuckWrap() {
    return Expanded(
        child: SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final duckInfoList = getDuckInfoList(constraints.biggest);
          return Stack(
            children: duckInfoList.map((duckInfo) {
              return Positioned(
                left: duckInfo.rect.left,
                top: duckInfo.rect.top,
                child: FocusWidget(
                  focusNode: duckInfo.focusNode,
                  onFocusChange: (bool value) {
                    setState(() {
                      for (var item in duckInfoList) {
                        changeDuckStatus(item, item == duckInfo, false);
                      }
                    });
                  },
                  onConfirm: () {
                    setState(() {
                      for (var item in duckInfoList) {
                        changeDuckStatus(
                            item, item == duckInfo, item == duckInfo);
                      }
                      // 统计处于激活状态的鸭子数量
                      int totalActiveDucks = 0;
                      for (var item in duckInfoList) {
                        if (item.duckIconData == IconFontValue.activeDuck ||
                            item.duckIconData ==
                                IconFontValue.focusAndActiveDuck) {
                          totalActiveDucks++;
                        }
                      }
                      if (lastTotalActiveDucks == totalActiveDucks ||
                          totalActiveDucks == 0) {
                        return;
                      }
                      lastTotalActiveDucks = totalActiveDucks;
                      AudioPlayManager.lowLatencyPlay(
                          countDucksAudList[totalActiveDucks - 1].aud);
                      if (totalActiveDucks == count) {
                        Future.delayed(Duration(milliseconds: 800), () {
                          AudioPlayManager.lowLatencyPlay(
                              countDucksResultAudList[totalActiveDucks - 1]
                                  .aud);
                        });
                      }
                    });
                  },
                  child: Icon(
                    duckInfo.duckIconData.value,
                    size: duckSize.height,
                  ),
                ),
              );
            }).toList(),
          );
        },
      ),
    ));
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return SafeAreaPageWrapper(
        padding: EdgeInsets.all(12),
        child: countDucksAudList.isEmpty || countDucksResultAudList.isEmpty
            ? Center(
                child: Text('数据加载中'),
              )
            : Column(
                children: [
                  renderTitle(),
                  renderDuckWrap(),
                ],
              ));
  }
}
